<template>
  <zeda-dialog
    v-model="visible"
    :title="(String(id).length <= 0 ? '新建' : '编辑') + '能耗阀值'"
    width="880px"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="model" :rules="rules" label-width="120px">
      <el-form-item label="所属用能单位" prop="sysDeptId">
        <CascaderSelect
          v-model="model.sysDeptId"
          :values="model.sysDeptId"
          varient="energy"
          @input="getNetworkList"
          :clearable="false"
          :filterable="true"
        ></CascaderSelect>
      </el-form-item>
      <el-form-item label="所属能耗终端" prop="deviceMonitoringNetworksId">
        <el-select
          v-model="model.deviceMonitoringNetworksId"
          placeholder="请选择所属能耗终端"
          size="small"
          :disabled="!model.sysDeptId"
          @change="getMeterDeviceCodes"
        >
          <el-option
            v-for="item in networkOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计量设备" prop="deviceMonitoringNetworksId">
        <el-select
          v-model="model.meterDeviceCode"
          placeholder="请选择计量设备"
          size="small"
          :disabled="!model.deviceMonitoringNetworksId"
        >
          <el-option
            v-for="item in deviceArchiveOptions"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="白名单设备" prop="deviceList">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          :disabled="!model.deviceMonitoringNetworksId"
          @click="handleAdd"
          >添加</el-button
        >
        <el-table v-loading="loading" :data="model.deviceList" max-height="400">
          <el-table-column
            prop="ruleId"
            label="设备"
            align="center"
            width="320"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'deviceList.' + scope.$index + '.whiteBlackId'"
                :rules="rules.whiteBlackId"
              >
                <el-select
                  size="small"
                  v-model="scope.row.whiteBlackId"
                  placeholder="规则"
                  style="width: 240px"
                >
                  <el-option
                    v-for="(item, index) in equipmentList"
                    :key="index"
                    :label="item.deviceName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="设备数量" align="center" width="240">
            <template slot-scope="scope">
              <el-form-item
                :prop="'deviceList.' + scope.$index + '.nums'"
                :rules="rules.nums"
              >
                <el-input-number
                  v-model="scope.row.nums"
                  :min="1"
                  label="描述文字"
                ></el-input-number
              ></el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index)"
                style="color: #f56c6c"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    />
  </zeda-dialog>
</template>
  <script>
import {
  deviceArchiveMeter,
  selectWhiteBlack,
  thresholdManageAdd,
  thresholdManageEdit,
  thresholdManageDetail,
} from "@/api/sub/portrayal";
import { getnetworks } from "@/api/system/dept";
import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
export default {
  components: {
    FormButton,
    CascaderSelect,
  },
  props: {
    id: { type: [Number, String], default: 0 },
    visible: { type: Boolean, default: false },
  },
  data() {
    return {
      loading: false,
      networkOptions: [],
      deviceArchiveOptions: [],
      equipmentList: [],
      model: {
        sysDeptId: "",
        deviceMonitoringNetworksId: "",
        meterDeviceCode: "",
        deviceList: [],
      },
      rules: {
        sysDeptId: [
          {
            required: true,
            message: "请选择所属用能单位",
            trigger: ["blur", "change"],
          },
        ],
        deviceMonitoringNetworksId: [
          {
            required: true,
            message: "请选择所属能耗终端",
            trigger: ["blur", "change"],
          },
        ],
        meterDeviceCode: [
          {
            required: true,
            message: "请选择计量设备",
            trigger: ["blur", "change"],
          },
        ],
        nums: [
          {
            required: true,
            message: "请填写设备数量",
            trigger: ["blur", "change"],
          },
        ],
        whiteBlackId: [
          {
            required: true,
            message: "请选择设备",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    getInfo() {
      let that = this;
      thresholdManageDetail(that.id)
        .then((res) => {
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.model = { ...that.model, ...res.data };
          getnetworks({
            sysDeptId: res.data.sysDeptId,
          })
            .then((data) => {
              if (data.code === 700) {
                that.$message.warning(data.msg);
                return false;
              }
              that.networkOptions = data.rows;
              that.getMeterDeviceCodes(
                that.model.deviceMonitoringNetworksId,
                1
              );
            })
            .catch((err) => {
              // this.$message.error("系统错误,请联系管理员!20001");
            });
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!301016");
        });
    },
    getNetworkList(data, type) {
      if (type !== 1) {
        this.model.deviceMonitoringNetworksId = "";
        this.model.meterDeviceCode = "";
      }
      getnetworks({
        sysDeptId: data[data.length - 1],
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.networkOptions = res.rows;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20001");
        });
    },
    getMeterDeviceCodes(val, type) {
      if (type !== 1) {
        this.model.meterDeviceCode = "";
      }
      let data = this.networkOptions.find((_) => _.id === val);
      selectWhiteBlack({
        subareaType: data.energySubarea,
        subareaChildType: data.energySubareaChild,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.equipmentList = res.data
            .map((item) => {
              item.nums = "";
              return item;
            })
            .filter((_) => _.whiteBlackFlag === 1);
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!301013");
        });
      deviceArchiveMeter({
        monitoringNetworkId: val,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.deviceArchiveOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!3001011");
        });
    },
    // 新增一行
    handleAdd() {
      let obg = {
        nums: 1,
        whiteBlackId: "",
      };
      this.model.deviceList.push(obg);
    },
    //删除
    handleDelete(index) {
      this.model.deviceList.splice(index, 1);
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            ...this.model,
            sysDeptId: this.model.sysDeptId[this.model.sysDeptId.length - 1],
          };
          this.loading = true;
          if (this.id) {
            thresholdManageEdit(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!301015");
              });
          } else {
            thresholdManageAdd(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!301014");
              });
          }
        } else {
          return false;
        }
      });
    },
    handleClose(status) {
      this.model = {
        sysDeptId: "",
        deviceMonitoringNetworksId: "",
        meterDeviceCode: "",
        deviceList: [],
      };
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>
